<template>
    <div class="app-container">
      <div class="filter-container">
        <el-input
        :disabled="userState"
          v-model="queryParams.userId"
          placeholder="用户编号"
          style="width: 250px;"
          class="filter-item"
          @keyup.enter.native="queryBtn"
        />
  
        <el-input
        :disabled="userState"
          v-model="queryParams.parkfieldName"
          placeholder="场站名称"
          style="width: 250px;margin-left:5px;"
          class="filter-item"
          @keyup.enter.native="queryBtn"
        />
        <el-input
        :disabled="userState"
          v-model="queryParams.lockMac"
          placeholder="设备编号"
          style="width: 250px;margin-left:5px;"
          class="filter-item"
          @keyup.enter.native="queryBtn"
        />

        <el-select style="margin-left:5px;" v-model="queryParams.isShowOcc" placeholder="选择占位费处理类型">
            <el-option key="0" label="全部" :value="99"></el-option>
            <el-option key="1" label="占位费已缴纳" :value="1"></el-option>
            <el-option key="2" label="占位费未缴纳" :value="2"></el-option>
            <el-option key="3" label="已缴纳退费处理" :value="3"></el-option>
            <el-option key="4" label="未缴纳处理" :value="4"></el-option>
          </el-select>
  <br/>
        <el-date-picker
        :disabled="userState"
          v-model="queryParams.startTime"
          value-format="yyyy-MM-dd HH:mm:ss"
          style="width: 250px;margin-top: 10px;"
          type="datetime"
          placeholder="请选择开始时间"
        ></el-date-picker>
  
         <el-date-picker
         :disabled="userState"
          v-model="queryParams.endTime"
          value-format="yyyy-MM-dd HH:mm:ss"
          style="width:250px;margin-left:5px;"
          type="datetime"
          placeholder="请选择结束时间"
        
        ></el-date-picker>
     
  
        <el-button
        :disabled="userState"
          v-waves
          class="filter-item"
          type="primary"
          style="margin-left:20px;"
          icon="el-icon-search"
          @click="queryBtn"
        >
          查询
        </el-button>
        <el-button
        :disabled="userState"
          v-waves
          :loading="downloadLoading"
          class="filter-item"
          type="primary"
          icon="el-icon-download"
          @click="checkDate"
        >
          导出
        </el-button>
      <span style="float: right;
      margin-right: 20px;
      font-weight: 600;color: #494949;">当前账号：<span style="color: #ff770f;">{{title}}</span></span>
    
    </div>
   
  
      <el-table
        :header-cell-style="{ background: '#ffffff', color: '#000000' }"
        :key="tableKey"
        :row-class-name="tableRowClassName"
        v-loading="listLoading"
        :data="list"
        border
        fit
        highlight-current-row
        style="
          width: 100%;
          font-size: 15px;
          box-shadow: 1px 1px 8px #cdcdcd;
          border: 0px;
        "
      >
        <!-- <el-table-column
          label="ID"
          prop="id"
          sortable="custom"
          align="center"
          width="80"
          :class-name="getSortClass('id')"
        >
          <template slot-scope="{ row }">
            <span>{{ row.id }}</span>
          </template>
        </el-table-column> -->
  
        <el-table-column label="用户编号" min-width="150px">
          <template slot-scope="{ row }">
            <span>{{ row.userId }}</span>
          </template>
        </el-table-column>
  
        <el-table-column label="设备名称" min-width="150px">
          <template slot-scope="{ row }">
            <span>{{row.lockName}}</span>
          </template>
        </el-table-column>
  
        <el-table-column label="场站名称" min-width="150px">
          <template slot-scope="{ row }">
            <span>{{row.parkfieldName}}</span>
          </template>
        </el-table-column>
  
        <el-table-column label="设备编号" width="150px" align="center">
          <template slot-scope="{ row }">
            <span>{{ row.lockMac }}</span>
          </template>
        </el-table-column>
  
        <!-- <el-table-column label="开始时间" width="165px" align="center">
          <template slot-scope="{ row }">
            <span>{{ sub(row.startTime) }}</span>
          </template>
        </el-table-column>
  
        <el-table-column label="结束时间" width="165px" align="center">
          <template slot-scope="{ row }">
            <span>{{ sub(row.endTime) }}</span>
          </template>
        </el-table-column> -->
  
        <el-table-column label="产生时间" width="165px" align="center">
          <template slot-scope="{ row }">
            <span>{{ sub(row.leaveTime) }}</span>
          </template>
        </el-table-column>
  
  
  
        <el-table-column label="占位时间" width="100px" align="center">
          <template slot-scope="{ row }">
            <span>{{ row.occupiedTime }}</span>
          </template>
        </el-table-column>

  
        <el-table-column label="占位费" width="100px" align="center">
          <template slot-scope="{ row }">
            <span>{{ row.occupiedFee }}</span>
          </template>
        </el-table-column>

        <el-table-column label="支付时间" width="100px" align="center">
          <template slot-scope="{ row }">
            <span>{{ row.payOccTime }}</span>
          </template>
        </el-table-column>

        
  
        <el-table-column label="退款时间" width="100px" align="center">
          <template slot-scope="{ row }">
            <span>{{ row.refundOccDate }}</span>
          </template>
        </el-table-column>
  
        <el-table-column label="状态" width="180px" align="center">
          <template slot-scope="{ row }">
            <!-- <span>{{ row.isShowOcc }}</span> -->
            <el-tag
            v-if="row.isShowOcc == 0"
            size="medium"
            type="primary"
            effect="dark"
            style="font-size: 14px"
            >无占位费</el-tag
          >
          <el-tag
            v-else-if="row.isShowOcc == 1"
            size="medium"
            type="success"
            effect="dark"
            style="font-size: 14px"
            >占位费已缴纳</el-tag
          >
           <el-tag
            v-else-if="row.isShowOcc == 2"
            size="medium"
            type="warning"
            effect="dark"
            style="font-size: 14px"
            >占位费未缴纳</el-tag
          >
          <el-tag
            v-else-if="row.isShowOcc == 3"
            size="medium"
            type="success"
            effect="dark"
            style="font-size: 14px"
            >已缴纳退费</el-tag
          >
          <el-tag
            v-else-if="row.isShowOcc == 4"
            size="medium"
            type="danger"
            effect="dark"
            style="font-size: 14px"
            >未缴纳退费</el-tag
          >
          <el-tag v-else size="medium" type="Info" style="font-size: 14px">{{
            row.isShowOcc
          }}</el-tag>
          </template>
        </el-table-column>

        <el-table-column label="订单编号" min-width="150px">
          <template slot-scope="{ row }">
            <span>{{ row.orderId }}</span>
          </template>
        </el-table-column>
  
      </el-table>
  
   
  
      <el-row>
        <el-col :span="24" class="page-tool">
          <el-pagination
            layout="total,sizes,prev, pager,next,jumper"
             style="margin-top: 10px;"
            :page-size="pageSize"
            :total="total"
            :page-sizes="[10, 20, 30, 40]"
            @size-change="handlePageChange"
            @current-change="handleNoChange"
          ></el-pagination>
        </el-col>
      </el-row>
  
      <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" center width="1590px">
        <el-form
          ref="dataForm"
          :rules="rules"
          :model="temp"
          label-position="left"
          label-width="70px"
        >
         
        <!-- <el-image 
      style="width: 100%;"
      :src="url" 
      :preview-src-list="srcList">
    </el-image>
          -->
  
    <el-image 
      style="width:1536px;height:864px;"
      :src="url" 
      :preview-src-list="srcList">
      <div slot="error" class="image-slot" style="text-align:center">
          暂无图片
        </div>
    </el-image>
         
  
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false"> 关闭 </el-button>
       
        </div>
      </el-dialog>
  
      <el-dialog :visible.sync="dialogPvVisible" title="Reading statistics">
        <el-table
          :data="pvData"
          border
          fit
          highlight-current-row
          style="width: 100%"
        >
          <el-table-column prop="key" label="Channel" />
          <el-table-column prop="pv" label="Pv" />
        </el-table>
        <span slot="footer" class="dialog-footer">
          <el-button type="primary" @click="dialogPvVisible = false"
            >Confirm</el-button
          >
        </span>
      </el-dialog>
    </div>
  </template>
  
  <style>
  .el-table .warning-row {
    background: #fff5ee;
  }
  .el-table--enable-row-hover .el-table__body tr:hover > td {
    background-color: #fdc091;
  }
  .el-table__body tr.current-row > td {
    background-color: #fdc091;
  }
  </style>
  
  <script>
  import { listLcChargerLogDetails, exportOrder } from "@/api/order";
  import waves from "@/directive/waves"; // waves directive
  import { parseTime } from "@/utils";
  import Pagination from "@/components/Pagination"; // secondary package based on el-pagination
  import axios from "axios";
  import { getToken } from "@/utils/auth";
  import { listLcOccLogDetailsApi } from "@/api/car";
  import { getNickName, getTestUserName } from "../../utils/auth";
  
  const calendarTypeOptions = [
    { key: "CN", display_name: "China" },
    { key: "US", display_name: "USA" },
    { key: "JP", display_name: "Japan" },
    { key: "EU", display_name: "Eurozone" },
  ];
  
  // arr to obj, such as { CN : "China", US : "USA" }
  const calendarTypeKeyValue = calendarTypeOptions.reduce((acc, cur) => {
    acc[cur.key] = cur.display_name;
    return acc;
  }, {});
  
  export default {
    name: "ComplexTable",
    components: { Pagination },
    directives: { waves },
    filters: {
      statusFilter(status) {
        const statusMap = {
          published: "success",
          draft: "info",
          deleted: "danger",
        };
        return statusMap[status];
      },
      typeFilter(type) {
        return calendarTypeKeyValue[type];
      },
    },
    data() {
      
      return {
  
  
        url: '',
        tableKey: 0,
        list: [],
        pageNo: 1,
        queryParams: {
          userId: "",
          startTime: "",
          endTime:"",
          lockMac:"",
          parkfieldName:"",
          roleCode:"",
          isShowOcc:""
        },
        key:"",
        pageSize: 20,
        multipleSelection: [],
        total: 0,
        listLoading: true,
        listQuery: {
          pageNo: 1,
          pageSize: 20,
          name: undefined,
          phone: undefined,
          number: undefined,
          sort: "+id",
        },
        importanceOptions: [1, 2, 3],
        calendarTypeOptions,
        sortOptions: [
          { label: "ID Ascending", key: "+id" },
          { label: "ID Descending", key: "-id" },
        ],
        statusOptions: ["published", "draft", "deleted"],
        showReviewer: false,
        temp: {
          id: undefined,
          importance: 1,
          remark: "",
          timestamp: new Date(),
          title: "",
          type: "",
          status: "published",
        },
        dialogFormVisible: false,
        dialogStatus: "",
        textMap: {
          update: "查看",
          create: "查看",
        },
        dialogPvVisible: false,
        title:"",
        pvData: [],
        rules: {
          type: [
            { required: true, message: "type is required", trigger: "change" },
          ],
          timestamp: [
            {
              type: "date",
              required: true,
              message: "timestamp is required",
              trigger: "change",
            },
          ],
          title: [
            { required: true, message: "title is required", trigger: "blur" },
          ],
        },
        downloadLoading: false,
        
      };
    },
  
    computed: {
      userState () {
        return getNickName() === getTestUserName();
      }
    },
  
    created() {
      //   this.getList()
      this.getStartTime();
      this.getendTime();
    },
    mounted: function () {
      this.key = localStorage.getItem("key");
      this.title = localStorage.getItem("title");
      this.queryParams.roleCode = localStorage.getItem("key");
      this.$nextTick(function () {
        this.loadorder(this.pageNo, this.pageSize);
      });

    },
    methods: {
 
  
       change(val) {
        console.log(val)
      },
  
      getStartTime () {
      let date = new Date()
      let y = date.getFullYear()
      let m = date.getMonth() + 1
      m = m < 10 ? '0' + m : m
      let d = '01'   
      let hh = '00'            
      let mm = '00'         
      let ss = '00'
      let time = y + '-' + m + '-' + d + ' ' + hh + ':' + mm + ':' + ss
      this.queryParams.startTime = time;
  
    },
  
      getendTime () {
      let date = new Date()
      let y = date.getFullYear()
      let d = date.getDate()
      let m = date.getMonth() + 1
      m = m < 10 ? '0' + m : m
     
      let hh = '23'            
      let mm = '59'         
      let ss = '59'
      let time = y + '-' + m + '-' + d + ' ' + hh + ':' + mm + ':' + ss
      this.queryParams.endTime = time;
    },
  
  
      tableRowClassName({ row, rowIndex }) {
        if (rowIndex % 2 == 0) {
          return "warning-row";
        }
        return "";
      },
      sub(value) {
        if (value === null || undefined) {
          return "";
        } else {
          value = value.substring(0, 16);
          return value;
        }
      },
      //列表页码的触发事件
      handlePageChange(pageSize) {
        this.pageSize = pageSize;
        this.loadorder(this.pageNo, this.pageSize);
      },
      handleNoChange(pageNo) {
        this.pageNo = pageNo;
        this.loadorder(this.pageNo, this.pageSize);
      },
      handleTableChange(val) {
        this.multipleSelection = val;
      },
      loadorder(pageNo, pageSize) {
        let _this = this;
        _this.loading = true;
        listLcOccLogDetailsApi({
          pageNo: pageNo,
          pageSize: pageSize,
          userId:_this.queryParams.userId,
          parkfieldName:_this.queryParams.parkfieldName,
          lockMac: _this.queryParams.lockMac,
          isShowOcc:_this.queryParams.isShowOcc,
          startTime: _this.queryParams.startTime,
          endTime: _this.queryParams.endTime,
          roleCode:_this.key
        }).then((response) => {
          _this.list = response.data.dataList;
          _this.total = response.data.totalNum;
          setTimeout(() => {
            _this.listLoading = false;
          }, 1 * 1000);
        });
      },
  
  
      queryBtn () {
        let _this = this
        _this.loading = true
        if(_this.queryParams.startTime == ""|| _this.queryParams.startTime == null){
          alert("开始时间不能为空！");
          return false
        }

        if(_this.queryParams.endTime == ""|| _this.queryParams.endTime == null){
          alert("结束时间不能为空！");
          return false
        }

       var stime = new Date(this.queryParams.startTime).getTime();
         var etime = new Date(this.queryParams.endTime).getTime();
         var day = (etime - stime)/(24*60*60*1000);
      if (day <= 0) {
          alert("结束时间不能小于开始时间");
      }
         else if (day > 370) {
          alert("时间间隔不能大于365天！");
         }
      else{
      _this.loadorder(_this.pageNo, _this.pageSize);
      }
  
       
      },
  
      resetTemp() {
        this.temp = {
          id: undefined,
          importance: 1,
          remark: "",
          timestamp: new Date(),
          title: "",
          status: "published",
          type: "",
        };
      },
      handleCreate() {
        this.resetTemp();
        this.dialogStatus = "create";
        this.dialogFormVisible = true;
        this.$nextTick(() => {
          this.$refs["dataForm"].clearValidate();
        });
      },
      createData() {
        this.$refs["dataForm"].validate((valid) => {
          if (valid) {
            addCar(this.temp).then(() => {
         //     this.getList();
              this.dialogFormVisible = false;
              this.$notify({
                title: "Success",
                message: "Created Successfully",
                type: "success",
                duration: 2000,
              });
            });
          }
        });
      },
      handleUpdate(row) {
        console.log('1111111111111111111111111111111');
        this.url = '';
        this.temp = Object.assign({}, row); // copy obj
        this.temp.timestamp = new Date(this.temp.timestamp);
        this.dialogStatus = "查看";
        this.dialogFormVisible = true;
        console.log('1111111111111111111111111111111',this.url);
        this.url = row.vehicleUrl;
        this.$nextTick(() => {
          this.$refs["dataForm"].clearValidate();
        });
        console.log('222222222222222222222222222',this.url);
      },
      updateData() {
        this.$refs["dataForm"].validate((valid) => {
          if (valid) {
            updateCar(this.temp).then(() => {
         //     this.getList();
              this.dialogFormVisible = false;
              this.$notify({
                title: "Success",
                message: "Update Successfully",
                type: "success",
                duration: 2000,
              });
            });
          }
        });
      },
      handleDelete(row, index) {
        this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }).then(() => {
          deleteCar({ id: row.id }).then(() => {
       //     this.getList();
            this.dialogFormVisible = false;
            this.$notify({
              title: "Success",
              message: "Delete Successfully",
              type: "success",
              duration: 2000,
            });
          });
        });
      },
      handleFetchPv(pv) {
        fetchPv(pv).then((response) => {
          this.pvData = response.data.pvData;
          this.dialogPvVisible = true;
        });
      },
  
      checkDate(){
  // var stime = new Date(this.queryParams.startTime.replace(/-/g,'/'));
  // var etime = new Date(this.queryParams.endTime.replace(/-/g,'/'));

  let _this = this

  if(_this.queryParams.startTime == ""|| _this.queryParams.startTime == null){
          alert("开始时间不能为空！");
          return false
        }

        if(_this.queryParams.endTime == ""|| _this.queryParams.endTime == null){
          alert("结束时间不能为空！");
          return false
        }

      var stime = new Date(this.queryParams.startTime).getTime();
      var etime = new Date(this.queryParams.endTime).getTime();
      var day = (etime - stime)/(24*60*60*1000);
    if(stime=='' || etime==''){
      alert("请输入开始时间和结束时间");
    }else if (day <= 0) {
          alert("结束时间不能小于开始时间");
      }else if(day>0 && day <= 730){
          this.handleDownload();
      }else if(day>730){
      alert("开始时间与结束时间差距不得大于2年");
    }
  
   // this.handleDownload();
  
      },
      handleDownload() {
        axios({
          method: "GET",
          url: "/vehicleMap/lcchargerlog/exportOccLog",
          params:this.queryParams,
          headers: { pacargle: getToken() },
          responseType: "blob", //返回是个文件
        }).then((response) => {
          this.download(response); //then直接下载，方法在下边
        });
      },
      download(res) {
        let blob = new Blob([res.data], { type: "text/xls,charset=UTF-8" }); //type是文件类，详情可以参阅blob文件类型
        // 创建新的URL并指向File对象或者Blob对象的地址
        const blobURL = window.URL.createObjectURL(blob);
        // 创建a标签，用于跳转至下载链接
        const tempLink = document.createElement("a");
        tempLink.style.display = "none";
        tempLink.href = blobURL;
        tempLink.setAttribute(
          "download",
          decodeURI(
            res.headers["content-disposition"].split(";")[1].split("=")[1]
          )
        );
        // 兼容：某些浏览器不支持HTML5的download属性
        if (typeof tempLink.download === "undefined") {
          tempLink.setAttribute("target", "_blank");
        }
        // 挂载a标签
        document.body.appendChild(tempLink);
        tempLink.click();
        document.body.removeChild(tempLink);
        // 释放blob URL地址
        window.URL.revokeObjectURL(blobURL);
      },
      formatJson(filterVal) {
        return this.list.map((v) =>
          filterVal.map((j) => {
            if (j === "timestamp") {
              return parseTime(v[j]);
            } else {
              return v[j];
            }
          })
        );
      },
      getSortClass: function (key) {
        const sort = this.listQuery.sort;
        return sort === `+${key}` ? "ascending" : "descending";
      },
    },
  };
  </script>
  